<template>
  <div class="profile-page">
    <header-nav />
    
    <!-- <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->

    <div class="main-content">
      <!-- 统一导航菜单 -->
      <user-nav-menu active-menu="profile" />

      <div class="profile-container">
        <el-row :gutter="20">
          <!-- 左侧用户信息卡片 -->
          <el-col :span="8">
            <el-card class="user-card" v-loading="loading">
              <div class="user-avatar">
                <el-upload
                  class="avatar-uploader"
                  :action="`${baseURL}/api/user/avatar`"
                  :headers="{ Authorization: `Bearer ${token}` }"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                  name="file"
                >
                  <el-avatar 
                    v-if="userInfo.avatar" 
                    :size="100" 
                    :src="getAvatarUrl(userInfo.avatar)"
                    @error="handleAvatarLoadError"
                  >
                    {{ userInfo.username?.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </div>
              <h2>{{ userInfo.username }}</h2>
              <p>{{ userInfo.email }}</p>
              <el-button type="primary" @click="showEditDialog = true">
                编辑资料
              </el-button>
            </el-card>
          </el-col>

          <!-- 右侧信息展示 -->
          <el-col :span="16">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>账户信息</span>
                </div>
              </template>
              
              <el-descriptions :column="1" border>
                <el-descriptions-item label="用户名">
                  {{ userInfo.username }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                  {{ userInfo.email }}
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">
                  {{ formatDate(userInfo.created_at) }}
                </el-descriptions-item>
                <el-descriptions-item label="最近登录">
                  {{ formatDate(userInfo.last_login) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <!-- 最近订单 -->
            <el-card class="mt-20">
              <template #header>
                <div class="card-header">
                  <span>最近订单</span>
                  <el-button text @click="router.push('/orders')">
                    查看全部
                  </el-button>
                </div>
              </template>
              
              <el-table :data="userInfo.recentOrders" stripe>
                <el-table-column prop="order_no" label="订单号" width="180" />
                <el-table-column prop="total_amount" label="金额" width="100">
                  <template #default="scope">
                    ¥{{ Number(scope.row.total_amount).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row.status)">
                      {{ getOrderStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="下单时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.created_at) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-card>

            <!-- 最近浏览 -->
            <div class="recent-section" v-if="userInfo.recentViews?.length">
              <h3>最近浏览</h3>
              <div class="recent-views">
                <div 
                  v-for="item in userInfo.recentViews" 
                  :key="item.id"
                  class="view-item"
                >
                  <!-- <el-image :src="item.image" :alt="item.name" /> -->
                  <el-image 
                    :src="getProductImageUrl(item.image)" 
                    :alt="item.name"
                    @error="() => handleProductImageError(item)" 
                  />
                  <p>{{ item.name }}</p>
                  <span class="price">¥{{ Number(item.price).toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人资料"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="editForm.oldPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="editForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import HeaderNav from '../components/HeaderNav.vue'
import UserNavMenu from '../components/UserNavMenu.vue'
import { ElMessage } from 'element-plus'
import axios from '../utils/axios'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const userInfo = ref({})
const loading = ref(true)
const showEditDialog = ref(false)
const editFormRef = ref(null)

// 从环境变量或 axios 配置中获取基础 URL
const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:5000'
const token = localStorage.getItem('token')

const editForm = ref({
  username: '',
  email: '',
  oldPassword: '',
  newPassword: ''
})

const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' }
  ]
}

const fetchUserInfo = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/user/profile');
    
    // 添加调试日志
    console.log('Profile response:', response);
    
    if (!response.data.success) {
      throw new Error(response.data.message || '获取数据失败');
    }
    
    userInfo.value = response.data.data;
    editForm.value = {
      username: response.data.data.username,
      email: response.data.data.email
    };
  } catch (error) {
    console.error('Profile error:', error);
    // 更详细的错误信息
    const errorMessage = error.response?.data?.message 
      || error.message 
      || '加载个人资料失败';
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

const handleUpdateProfile = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 分别处理基本信息和密码更新
        const { username, email, oldPassword, newPassword } = editForm.value;
        
        // 更新基本信息
        if (username !== userInfo.value.username || email !== userInfo.value.email) {
          await axios.put('/api/user/profile', { username, email });
        }
        
        // 如果填写了密码，则更新密码
        if (oldPassword && newPassword) {
          await axios.put('/api/user/password', { oldPassword, newPassword });
        }
        
        ElMessage.success('更新成功');
        showEditDialog.value = false;
        
        // 重置表单
        editForm.value = {
          username: userInfo.value.username,
          email: userInfo.value.email,
          oldPassword: '',
          newPassword: ''
        };
        
        // 刷新用户信息
        await fetchUserInfo();
      } catch (error) {
        console.error('Error:', error);
        ElMessage.error(error.response?.data?.message || '更新失败');
      }
    }
  })
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const getOrderStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

const getOrderStatusText = (status) => {
  const texts = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getAvatarUrl = (avatar) => {
  if (!avatar) return '';
  
  // 检查是否已经是完整的 URL
  if (avatar.startsWith('http')) return avatar;
  
  // 使用正确的基础 URL
  return `${baseURL}/uploads/${avatar}`;
}

const handleAvatarSuccess = (response) => {
  if (response.success) {
    userInfo.value.avatar = response.avatar;
    ElMessage.success('头像上传成功');
  }
};

const handleAvatarError = (error) => {
  console.error('Upload error:', error);
  ElMessage.error(error.message || '上传失败');
};

const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('头像必须是图片格式!')
  }
  if (!isLt5M) {
    ElMessage.error('头像大小不能超过 5MB!')
  }

  return isImage && isLt5M
}

const handleAvatarLoadError = () => {
  userInfo.value.avatar = 'avatars/default.png';
};

onMounted(() => {
  fetchUserInfo()
})
// 添加处理商品图片URL的函数
const getProductImageUrl = (image) => {
  if (!image) return '/images/default.png';
  
  // 检查是否已经是完整的 URL
  if (image.startsWith('http')) return image;
  
  // 使用正确的基础 URL
  return `${baseURL}/uploads/${image}`;
}

// 添加图片错误处理函数
const handleProductImageError = (item) => {
  console.error('Product image load error:', item.image);
  // 可以在这里设置默认图片
  item.image = 'default.png';
};
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-content {
  max-width: 1400px;
  margin: 60px auto 0;
  padding: 20px;
}

.profile-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.breadcrumb {
  margin: 20px 0;
}

.user-card {
  text-align: center;
  padding: 20px;
}

.user-avatar {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-20 {
  margin-top: 20px;
}

:deep(.el-descriptions) {
  margin: 20px 0;
}

:deep(.el-tag) {
  text-transform: capitalize;
}

.avatar-uploader {
  text-align: center;
  cursor: pointer;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-uploader:hover .avatar-uploader-icon {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

/* 最近浏览部分样式 */
.recent-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.recent-section h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.recent-views {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 15px;
}

.view-item {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 10px;
  background-color: #f9f9f9;
  text-align: center;
}

.view-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.view-item .el-image {
  width: 100%;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}

.view-item p {
  margin: 10px 0 5px;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.view-item .price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .recent-views {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .recent-views {
    grid-template-columns: repeat(1, 1fr);
  }
  
  .view-item .el-image {
    height: 100px;
  }
}
</style>
